<template>
  <div class="container">
    <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="租赁模式：" prop="order_rent_type_id">
            <el-select v-model.trim="form.order_rent_type_id" placeholder="请选择租赁模式" clearable>
              <el-option v-for="item in orderRentTypeList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="选择时间：" prop="start_time">
            <el-date-picker v-model="scheduleDate" type="datetimerange" range-separator="至" format="YYYY-MM-DD HH:mm:ss" value-format="x" start-placeholder="开始时间" @change="changeScheduleDate" end-placeholder="结束时间"> </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="平台佣金比例：" prop="platform_commission_ratio">
            <el-input v-model.trim="form.platform_commission_ratio" placeholder="请填写平台佣金比例"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="运营商佣金比例：" prop="merchant_operator_commission_ratio">
            <el-input v-model.trim="form.merchant_operator_commission_ratio" disabled placeholder="请填写运营商佣金比例"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="利润比例：" prop="investor_investment_ratio">
            <el-input v-model.trim="form.investor_investment_ratio" placeholder="请填写利润比例"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="运营商：" prop="merchant_operator_id">
            <el-input v-model="form.merchant_operator_name" disabled placeholder="请选择运营商"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" plain @click="handleSelectOperatorInfo">选择</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
    <SelectOperatorDialog v-model:edit-visible="editVisible" @handleSuccess="handleSelectedData" />
  </div>
</template>

<script setup lang="ts">
import SelectOperatorDialog from "@/components/user/operatorManager/allocateOperator/SelectOperatorDialog.vue";
import type { postOrPutType } from "@/constants";
import type { ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IAllocateOperator, IOrderRentType } from "@/types/user/allocateOperator";
import { commonInvestorDivideFundInfo } from "@/utils/api/investorDivideFund";
import type { IOperatorManagerList } from "@/types/user/operatorManager";
const { disabledbtn, loading, toggleState } = useState();

interface Props {
  orderRentTypeList: Array<IOrderRentType>;
}
const { orderRentTypeList } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });

const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
}>();

const isDisabledbtn = ref(false);
const editVisible = ref(false);
const formRef = useTemplateRef("formRef");
const methodType = ref<postOrPutType>("PUT");

const rules = reactive({
  order_rent_type_id: [{ required: true, message: "请选择租赁模式", trigger: "blur" }],
  merchant_operator_id: [{ required: true, message: "请选择运营商", trigger: "blur" }],
  platform_commission_ratio: [{ required: true, message: "请填写平台佣金比例", trigger: "blur" }],
  merchant_operator_commission_ratio: [{ required: true, message: "请填写运营商佣金比例", trigger: "blur" }],
  investor_investment_ratio: [{ required: true, message: "请填写投资商成本比例", trigger: "blur" }],
  start_time: [{ required: true, message: "请选择分配时间", trigger: "blur" }]
});
const form = defineModel<IAllocateOperator>("form", { required: true });
const scheduleDate = defineModel<Array<string>>("scheduleDate", { required: true });

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
/* 查询 创建时间更改事件 */
function changeScheduleDate(data: number[]) {
  if (data !== null) {
    form.value.start_time = data[0];
    form.value.end_time = data[1];
  } else {
    form.value.start_time = "";
    form.value.end_time = "";
  }
}
/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  form.value.merchant_operator_name = "";
  form.value.start_time = "";
  form.value.end_time = "";
  scheduleDate.value = [];
  isDisabledbtn.value = false;
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonInvestorDivideFundInfo(form.value, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  emit("handleInitData");
}

/* 请选择运营商 */
function handleSelectOperatorInfo() {
  editVisible.value = true;
}

/* 选择选中的投资商数据 */
function handleSelectedData(list: IOperatorManagerList[]) {
  form.value.merchant_operator_id = list[0].id;
  form.value.merchant_operator_name = list[0].username;
}
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}

.w-continer {
  display: flex;
  align-items: center;
  gap: 10px;
}
.draggable-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.recovery-valuation-info {
  margin: 20px 50px;
  .r-title {
    margin-bottom: 20px;
    margin-left: 20px;
    font-weight: bold;
  }
}
</style>
